import requests
from common.logger import *
import urllib3

# create a logger instance
logger = root_logger.getLogger("root.api_request")


# 禁用安全请求警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# charls证书，pem为False时，charls必须关闭windows proxy选项项，反之则开
# pem = "charles-ssl-proxying-certificate.pem"
pem = False


class UrlRequest:
    @staticmethod
    def url_request(method, url, data=None, json=None, name="接口", header_dic=None):
        """
        :param method: method(get/post/put/delete)
        :param url: 请求的url
        :param data: 请求参数，字典形式
        :param json: 请求参数，json形式
        :param name: 接口名字，用于输出log
        :param header_dic: header字典
        :return: 返回result字典
        """
        timeout = 10  # 设置超时时间
        result = {"result": None, "msg": None}
        # result接口返回的数据，msg用于输出展示的文字
        try:
            logger.info("开始请求接口=>> %s" % name)
            if method == "get":
                response = requests.get(url=url, params=data, headers=header_dic, timeout=timeout, verify=pem)
                # verify = pem ssl证书验证，解决开着charles报错的问题
                response.raise_for_status()  # 请求失败抛出异常
            elif method == "post":
                if data:
                    response = requests.post(url=url, data=data, headers=header_dic, timeout=timeout, verify=pem)
                else:
                    response = requests.post(url=url, json=json, headers=header_dic, timeout=timeout, verify=pem)
                response.raise_for_status()  # 请求失败抛出异常
            elif method == "put":
                if data:
                    response = requests.put(url=url, data=data, headers=header_dic, timeout=timeout, verify=pem)
                else:
                    response = requests.put(url=url, json=json, headers=header_dic, timeout=timeout, verify=pem)
                response.raise_for_status()  # 请求失败抛出异常
            elif method == "delete":
                if data:
                    response = requests.delete(url=url, data=data, headers=header_dic, timeout=timeout, verify=pem)
                else:
                    response = requests.delete(url=url, json=json, headers=header_dic, timeout=timeout, verify=pem)
                response.raise_for_status()  # 请求失败抛出异常
            else:
                msg = "method(get/post/put/delete)输入错误"
                result["msg"] = msg
                logger.error(msg)
                return result
        except requests.exceptions.RequestException as e:
            msg = "fail - %s，reason = %s" % (name, e)
            logger.error(msg)
            result["msg"] = msg
        else:
            logger.info("%s接口，请求完成=>>" % name)
            try:
                result["result"] = response.json()
            except:
                # 如果返回数据不是json格式，需要手动处理
                result["result"] = response.text
                msg = "success - %s接口----返回数据不是json格式，但接口请求成功，返回数据：%s" % (name, result["result"])
                logger.warning(msg)
        return result

